<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-16
 * Time: 9:14
 */

namespace app\seller\controller;

use app\common\controller\Seller;

use app\common\logic\MallLogic;
use app\common\model\FareTmpl;
use app\common\model\City;
use app\common\logic\SpecLogic;
use app\common\model\Type;
use app\common\logic\GoodsLogic;
use app\common\model\Spec;
use app\common\model\Company;
use app\common\model\CoType;
use think\Request;
class Mall extends Seller
{

    protected $authenticate=null;
    
    public function index()
    {
        $logic = new GoodsLogic();
       
        if(Request::instance()->isAjax()){
            $logic->setValue('size',20);
            $logic->setValue('paginate',1);
            //'status'=>3,
            $logic->setSql(['user_id'=>SID]);
            $list = $logic->prepareDataProvider();
            success($list);
        }else{
            return $this->fetch();
        }
        
    }
    
    
    public function down($id){
        
        $id = paramForm('id');
        $logic = new GoodsLogic();
        $rt = $logic->changeGoodsStatus($id,0);
        if($rt){
            success(null);
        }else{
            error('操作失败');
        }
        
    }
    
    public function up($id){
        $id = paramForm('id');
        $logic = new GoodsLogic();
        $rt = $logic->changeGoodsStatus($id,3);
        if($rt){
            success(null);
        }else{
            error('操作失败');
        }
        
    }
    
    public function add(){
    
        $rule = ['typeid|叶子类目id'=>'require'];
        $params = paramForm();
        $this->validate($params,$rule);
        
        $type = Type::get($params['typeid']);
        if(!$type){
            $this->error('叶子类目不存在','/mall/type');
        }


        $cotype = CoType::get(['co_id'=>SID]);
        if(!$cotype){
            $this->error('请先添加店铺商品分类','/co_type/add');
        }
        
        //约束发货区域、叶子类目、商品模板
        $this->assign('type',$type);
        $this->assign('provienceList',City::all(['parent_id'=>22]));
        $userId = $this->getSellerId();
        $fareList = FareTmpl::all(['status'=>1,'user_id'=>$userId]);
        
        //约束发货地址
        if(count($fareList)<1){
            $this->error('需要先添加发货模板哦','/fare_tmpl');
        }
        $this->assign('fareList',$fareList);

        $this->assign('coTypeList',CoType::all(['co_id'=>SID]));
        
        $specLogic = new SpecLogic();
        $specLogic->setValue('size',null);//有多少来多少。。
        $specLogic->setValue('width','val');//把值也带上
        $filter = ['type_id'=>$type['id'], 'is_attr'=>1];
        //约束属性
        
        $specLogic->setValue('condition',$filter);
        $attrs = $specLogic->prepareDataProvider();
        
        //约束规格
        $filter['is_attr'] = 0;
        $specLogic->setValue('condition',$filter);
//        var_dump($specLogic);die;
        $specs = $specLogic->prepareDataProvider();
    
        if(count($specs)<1){
            $this->error('该类目没有规格，请联系客服添加','/index');
        }
        
        $this->assign('attrLen',count($attrs));
        $this->assign('attrs',$attrs);
        $this->assign('specs',$specs);
        
        
        return $this->fetch();
    }
    
    /**
     * @return string|void
     */
    public function save(){
        
        $rule=[
            'type_id|叶子类目id'=>'require',
            'type_title|叶子类目名称'=>'require',
            'co_type_id|店铺自定义分类'=>'require',
            'unit|单位'=>'require',
            'fare_id|运费模板信息'=>'require',
            'price|基础价格'=>'require',
            'content|产品简介'=>'require',
            'user_id|发布人'=>'require'
        ];
        
        $params = paramForm();
        $params['user_id'] = $this->getSellerId();
        
        $this->validate($params,$rule);
        
        //存好图片
        $thumb = request()->file('thumb');
        if($thumb){
            $params['thumb']=$this->uploadToAlyun($thumb);
        }else{
            error('缩略图必传');
        }

        //存好图片
        $pic1 = request()->file('pic1');
        if($pic1){
            $params['pic1']=$this->uploadToAlyun($pic1);
        }
        $pic2 = request()->file('pic2');
        if($pic2){
            $params['pic2']=$this->uploadToAlyun($pic2);
        }
        $pic3 = request()->file('pic3');
        if($pic3){
            $params['pic3']=$this->uploadToAlyun($pic3);
        }
        $pic4 = request()->file('pic4');
        if($pic4){
            $params['pic4']=$this->uploadToAlyun($pic4);
        }
//
        $logic = new MallLogic();
        $goodsId = $logic->addGoods($params);

      
        //拿到货品id,开始搞属性和属性值
        $attrs = paramForm('attr');
        $postAttrs = [];
        if (isset($attrs)&&is_array($attrs)){
            foreach ($attrs as $attr){
                //存在===号
                if($attr&&strpos($attr,'===')>-1){
                    $tempArr = explode('===',$attr);
                    $attrInfo= Spec::get($tempArr[0]);
                    $postAttrs[] = ['attr_id'=>$tempArr[0],'title'=>$attrInfo['title'],'val'=>$tempArr[1],'goods_id'=>$goodsId];
                }
            }
            
            /**
             * 储存货品和属性的对应关系
             */
            $rt = $logic->addsGoodsAttr($postAttrs);
            
            if(!$rt){
                error('货品属性保存错误');
            }
        }
      
        

        $prices = $params['specprice'];
        $stocks = $params['stock'];
        $codes = $params['code'];
        $barcode = $params['barcode'];
        if(count($prices)!=count($stocks)){
            error('价格和库存数据不一致，请务必每项都填写');
        }
        $mallArr = [];
        foreach ($prices as $key=>$price){
            //过滤掉不合格的
            if($prices[$key]&&$stocks[$key]){
                $mallArr[] = ['price'=>$prices[$key],'stock'=>$stocks[$key],'code'=>$codes[$key],'barcode'=>$barcode[$key],'goods_id'=>$goodsId];
            }
        }
        $mallIds = $logic->adds($mallArr);
        if(!$mallIds){
            error('商品及规格信息保存错误');
        }
    
    
        /**
         * 储存货品和属性的对应关系
         */
        foreach ($mallIds as $key=>$mall){
            
            $specs = paramForm('spec');
            $postSpecs = [];
            if (isset($specs)&&is_array($specs)){
                foreach ($specs[$key] as $spec){
                    //存在===号
                    if($spec&&strpos($spec,'===')>-1){
                        $tempArr = explode('===',$spec);
//                        $specInfo = Spec::get(['type_id'=>1039,'title'=>$tempArr[0]]);
//                        $postSpecs[] = ['spec_id'=>$specInfo['id'],'title'=>$specInfo['title'],'val'=>$tempArr[1],'mall_id'=>$mall->id];
                        $specInfo = Spec::get($tempArr[0]);
//                        var_dump($specInfo['title']);
                        $postSpecs[] = ['spec_id'=>$tempArr[0],'title'=>$specInfo['title'],'val'=>$tempArr[1],'mall_id'=>$mall->id];
                    }
                }
                $rt = $logic->addsSpec($postSpecs);
                if(!$rt){
                    error('商品规格保存错误');
                }
            }
            
        }
        
       api(1,'商品信息发布成功',$goodsId);
        die;
        
        
    }
    
    public function type(){
        return $this->fetch();
    }
    
    public function getSpec(){
        
        $specLogic = new SpecLogic();
        
    }


    
}